<?php
namespace app\customer\controller;
use app\AdminRest;
use app\card\model\UserFollow;
use app\card\model\UserPhone;
use app\card\service\UserService;
use app\shop\model\IndexUser;
use think\App;
use think\facade\Db;
use think\Request;
use app\Common\model\LongbingUser as UserModel;
use app\Common\model\LongbingUserInfo as UserInfoModel;
use app\Common\model\LongbingCardUserMark as MarkModel;
use app\Common\model\LongbingCardCollection as CollectionModel;
use app\Common\model\LongbingClientInfo as ClientInfoModel;
use app\im\model\ImReplyType as ReplyTypeModel;
use app\im\model\ImMyReply as ReplyModel;
use app\customer\model\LongbingCardQuestionnaire as QuestionnaireModel;
use app\customer\model\LongbingCardQuestion as QuestionModel;
use app\admin\model\AppConfig as QuestionnairConfig;
use app\customer\model\LongbingCardAnswer as AnswerModel;
use app\dynamic\model\CardTimeline;
use app\customer\model\StaffHand;
use app\radar\model\RadarCount;
use longbingcore\wxcore\Excel;


class Admin extends AdminRest
{
    public function __construct(App $app) {
        parent::__construct($app);
    }

    //获取客户列表
    public function listCustomer()
    {
        
        //获取查询参数
        $param = $this->_param;
        //获取分页数据
        $page_config = array(
            'page' => 1,
            'page_count' => 1
        );

        /**
         * 授权信息判断
         * @param empower 0全部  1授权手机号  2授权登陆信息/头像
         */
        $empower = isset($param['empower'])?$param['empower']:0;

        if(isset($param['page']) && $param['page'] > 0) $page_config['page'] = $param['page'];
        if(isset($param['page_count']) && $param['page_count'] > 0) $page_config['page_count'] = $param['page_count'];
        //获取数据
        $customer_model = new UserModel();
        $filter['uniacid'] = $this->_uniacid;
        if(isset($param['nickName']) && $param['nickName'] != null) $filter['nickName'] = $param['nickName'];
        //mark(0,未跟进 1，跟进中 ，2已成交 ，3 未成交)
        if(isset($param['mark']) &&  !empty($param['mark'])) $filter['mark'] = $param['mark'];
//      if(isset($param['follow'])) $filter['follow'] = $param['follow'];
//      if(isset($param['is_phone'])) $filter['is_phone'] = $param['is_phone'];
        if(isset($param['follow']) && !empty($param['follow'])) $filter['deal'] = $param['follow'];
//        if(isset($param['is_phone']) && !empty($param['is_phone'])) $filter['is_phone'] = $param['is_phone']; #2020/5/12 lichuanming 注释
//      $customers = $customer_model->listCustomer($filter ,$page_config);
        /**
         * 2020/5/12 修改 -lichuanming
         */
        if($empower == 1) $filter['is_phone'] = 1;
        if($empower == 2) $filter['avatarUrl'] = ['<>',''];
        //查看是否授权昵称
        if(!empty($param['status'])){

//            dump($param['status']);exit;

            $filter['avatarUrl'] = $param['status']==1?['<>','']:'';

        }

        $customers_data = $customer_model->listCustomerData($filter ,$page_config);
        $customers      = $customers_data['data'];

        //数据处理
        foreach($customers as $key => $val)
        {
            switch($val['mark'])
            {
                case 1:
                    $customers[$key]['mark'] = lang('In the follow up');
                    $customers[$key]['mark_status'] = lang('not traded');
                    break;
                case 2:
                    $customers[$key]['mark'] = lang('traded');
                    $customers[$key]['mark_status'] = lang('traded');
                    break;
                default:
                    $customers[$key]['mark'] = lang('not follow up');
                    $customers[$key]['mark_status'] = lang('not traded');
                    break;
            }
//          if(isset($val['staff_id'])){
//              $staff = longbingGetUserInfo($val['staff_id'] ,$this->_uniacid);
//              if(isset($staff['name'])) $customers[$key]['mark_staff'] = $staff['name'];
//          }else{
//              $customers[$key]['mark_staff'] = null;
//          }
            $customers[$key]['AI'] = rand(0, 100);
        }
        //生成返回数据
        $page_config['total'] = $customers_data['count'];
        $page_config['total_page'] = (int)($page_config['total'] / $page_config['page_count']);
        if(($page_config['total'] % $page_config['page_count']) > 0) $page_config['total_page'] = $page_config['total_page'] + 1;
        $result    = $page_config;
        $result['data'] = $customers;

        //返回数据
        return $this->success($result);
    }




    public function listCustomerV2()
    {
        //获取查询参数
        $param = $this->_param;

        $customer_model   = new UserModel();

        $param['uniacid'] = $this->_uniacid;

        $customers_data   = $customer_model->listCustomerDataV2($param);

        if(!empty($customers_data['data'])){
            //数据处理
            foreach($customers_data['data'] as $key => &$val)
            {
                switch($val['mark'])
                {
                    case 1:
                        $val['mark'] = lang('In the follow up');
                        $val['mark_status'] = lang('not traded');
                        break;
                    case 2:
                        $val['mark'] = lang('traded');
                        $val['mark_status'] = lang('traded');
                        break;
                    default:
                        $val['mark'] = lang('not follow up');
                        $val['mark_status'] = lang('not traded');
                        break;
                }
                $val['AI'] = rand(0, 100);
            }
        }
        //返回数据
        return $this->success($customers_data);
    }

    /**
     * @author chenniang
     * @DataTime: 2020-08-07 09:17
     * @功能说明:客户列表导出
     */
    public function listCustomerExcel(){
        //获取查询参数
        $param = $this->_param;

        $customer_model   = new UserModel();

        $param['uniacid'] = $this->_uniacid;

        $param['limit']   = 99999999;

        $customers_data   = $customer_model->listCustomerDataV2($param);

        $name   = date('Y-m-d',time()).'——'.'客户列表';

        $header = [

            '微信昵称',

            '授权手机号',

            '加入时间',

            '跟进状态',

            '跟进员工',

            '意向度',

            '成交时间',

            '导入客户',

            '备注',
        ];

        $new_data = [];

        if(!empty($customers_data['data'])){
            //数据处理
            foreach($customers_data['data'] as $key => &$val)
            {
                switch($val['mark'])
                {
                    case 1:
                        $val['mark'] = lang('In the follow up');
                        $val['mark_status'] = lang('not traded');
                        break;
                    case 2:
                        $val['mark'] = lang('traded');
                        $val['mark_status'] = lang('traded');
                        break;
                    default:
                        $val['mark'] = lang('not follow up');
                        $val['mark_status'] = lang('not traded');
                        break;
                }
                $val['AI'] = rand(0, 100);

                $info   = array();

                $info[] = $val['nickName'];

                $info[] = $val['phone'];

                $info[] = date('Y-m-d H:i:s',$val['create_time']);

                $info[] = $val['mark'] ;

                $info[] = $val['mark_staff'];

                $info[] = $val['rate_text'];

                $info[] = $val['update_time']=='-'?'':date('Y-m-d H:i:s',$val['update_time']);

                $info[] = $val['import']==0?'否':'是';

                $info[] = $val['remark_name'];

                $new_data[] = $info;
            }

        }

        $excel   = new Excel();

        $fileName=$excel->excelExport($name,$header,$new_data);
        //返回数据
        return $this->success($fileName);

    }



    //获取客户详情
    public function getCustomer()
    {
        //获取查询参数
        $param = $this->_param;
        if(!isset($param['customer_id']) || empty($param['customer_id'])) return $this->error(lang('not customer id'));
        //获取数据
        $customer_model = new UserModel();
        $customer = $customer_model->getCustomer(['uniacid' => $this->_uniacid ,'customer_id' => $param['customer_id']]);
        if(empty($customer)) return $this->success($customer);
        //数据处理
        switch($customer['mark'])
        {
            case 1:
                $customer['mark'] = lang('In the follow up');
                $customer['mark_status'] = lang('not traded');
                break;
            case 2:
                $customer['mark'] = lang('traded');
                $customer['mark_status'] = lang('traded');
            default:
                $customer['mark'] = lang('not follow up');
                $customer['mark_status'] = lang('not traded');
        }
        if(isset($customer['staff_id'])){
            $staff = longbingGetUserInfo($customer['staff_id'] ,$this->_uniacid);
            if(isset($staff['name'])) $customer['mark_staff'] = $staff['name'];
        }
        //数据返回
        return $this->success($customer);
    }
    //分配客户
    public function allotCustomer()
    {
        //获取参数
        $input = $this->_input;
        if(isset($input['data'])) $input = $input['data'];
        //判断参数是否存在
        if(!isset($input['customer_id']) || empty($input['customer_id'])) return $this->error(lang('not customer id'));
        if(!isset($input['staff_id']) || empty($input['staff_id'])) return $this->error(lang('not staff id'));
        //获取客户信息
        $customer_model = new UserModel();
        $customer = $customer_model->getCustomer(['uniacid' => $this->_uniacid ,'customer_id' => $input['customer_id']]);
        if(empty($customer)) return $this->error(lang('not customer'));
        //获取当前已分配的客服信息
        $old_staff_ids = [];
        $collection_model = new CollectionModel();
        $collections      = $collection_model->listCollection(['uid' => $input['customer_id'] ,'uniacid' =>$this->_uniacid ,'intention' => 1]);
        foreach($collections as $collection)
        {
            if(!in_array($collection['to_uid'], $old_staff_ids)) $old_staff_ids[] = $collection['to_uid'];
        }
        //检查员工
        $staff_ids = $input['staff_id'];
        if(!is_array($staff_ids)) $staff_ids = explode(',', $staff_ids);
        foreach($staff_ids as $key => $staff_id)
        {
            if(in_array($staff_id, $old_staff_ids)) 
            {
                unset($old_staff_ids[array_search($staff_id, $old_staff_ids)]);
                unset($staff_ids[$key]);
            }else{
                $staff = longbingGetUserInfo($staff_id ,$this->_uniacid);
                if(empty($staff) || empty($staff['is_staff'])) unset($staff_ids[$key]);
            }
        }
        
        //删除原有员工分配数据
        if(!empty($old_staff_ids))
        {
            $collection_model = new CollectionModel();
            $collection_model->delCollection([['uniacid' ,'=' ,$this->_uniacid] ,['uid' , '=' , $input['customer_id']] ,['to_uid' ,'in' , $old_staff_ids] ]);
        }
        
        //创建新的员工分配数据
        if(!empty($staff_ids))
        {
            foreach($staff_ids as $staff_id) 
            {
                $collection_model = new CollectionModel();
                $data = $collection_model->getCollection(['uniacid' => $this->_uniacid ,'uid' => $input['customer_id'] ,'to_uid' => $staff_id]);
                if(!empty($data)  ) 
                {
                    if(empty($data['intention']))
                    {
                        $collection_model = new CollectionModel();
                        $collection_model->updateCollection(['id' => $data['id']] ,['intention' => 1]);
                    }
                }else{
                    $data = ['uniacid' => $this->_uniacid ,'uid' => $input['customer_id'] ,'to_uid' => $staff_id , 'distribution' => 1 ,'intention' => 1];
                    $collection_model = new CollectionModel();
                    $collection_model->createCollection($data); 
                }
            }
            //生成分配数据
//          $mark_model = new MarkModel();
//          $result     = $mark_model->createMark(['user_id' => $input['customer_id'] ,'staff_id' => $input['staff_id'] ,'uniacid' => $this->_uniacid]);
        }
        return $this->success(true);
    }

    public function getAllotCustomer()
    {
        //获取数据
        $uniacid = $this->_uniacid;
        //获取客户id
        $param   = $this->_param;
        //判断客户id是否存在
        if(!isset($param['customer_id'])) return $this->error(lang('not customer'));
        //判断客户是否是客户
        $customer = longbingGetUser($param['customer_id'] ,$uniacid);
        if(empty($customer) || !empty($customer['is_staff'])) return $this->error(lang('not customer'));
        //获取分配数据
        $staff_ids = [];
        $collection_model = new CollectionModel();
        $collections      = $collection_model->listCollection(['uid' => $param['customer_id'] ,'uniacid' => $uniacid]);
        foreach($collections as $val){
            if(isset($val['to_uid']) && !empty($val['to_uid'])) {
                $staff = longbingGetUserInfo($val['to_uid'] ,$uniacid);
                if(!empty($staff) && isset($staff['is_staff']) && !empty($staff['is_staff']) && !in_array($val['to_uid'], $staff_ids))
                {
                    $staff_ids[] = $val['to_uid'];
                }
            }
        }
        
        return $this->success($staff_ids);
    }
    //查询客户问卷
    public function getCustomerQuestionnaire()
    {
        //获取数据
        $param = $this->_param;
        //判断数据是否存在
        if(!isset($param['user_id'])) return $this->error(lang('user id not exist'));
        //判断用户是否存在
        $user = longbingGetUser($param['user_id'] ,$this->_uniacid);
        if(empty($user)) return $this->error(lang('user not exist'));
        //获取问卷详情
        $qn_model = new QuestionnaireModel();
        $qn = $qn_model->getQuestionnaire(['uniacid' => $this->_uniacid ,'status' => 1]);
        if(empty($qn)) return $this->success($qn);
        foreach($qn['question'] as $key => $val)
        {
            if(isset($val['id']) && !empty($val['id'])){
                $answer_model = new AnswerModel();
                $answer = $answer_model->getAnswer(['uniacid' => $this->_uniacid ,'q_id' => $val['id'] ,'user_id' => $param['user_id']]);
                $qn['question'][$key]['answer'] = lang('not answer');
                if(isset($answer['answer'])) $qn['question'][$key]['answer'] = $answer['answer'];
            }
        }
        return $this->success($qn);
    }
    //员工交接
    public function staffHandover()
    {
        //获取参数
        $input = $this->_input;
        if(isset($input['data'])) $input = $input['data'];
        //判断参数是否存在
        if(!isset($input['to_staff_id']) || empty($input['to_staff_id'])) return $this->error(lang('not staff id'));
        if(!isset($input['staff_id']) || empty($input['staff_id'])) return $this->error(lang('not staff id'));
        if(in_array($input['staff_id'], [$input['to_staff_id']])) return $this->error(lang('not handover selef'));

        $is_d = Db::name('longbing_card_user_info')->where(['fans_id'=>$input['staff_id']])->value('is_default');

        if(UserService::getDefaultStraffNumber($this->_uniacid) == 1&&$is_d==1 ){

            return $this->error( '必须保留一位推荐员工' );

        }

        //获取用工信息
        $staff = longbingGetUserInfo($input['staff_id'] ,$this->_uniacid );
        if(empty($staff) || empty($staff['is_staff'])) return $this->error(lang('not staff'));
        $to_staff = longbingGetUserInfo($input['to_staff_id'] ,$this->_uniacid);
        if(empty($to_staff) || empty($to_staff['is_staff'])) return $this->error(lang('not accept staff'));
        //修改数据
        //交接客户
        $customer_model = new UserModel();
        $result = $customer_model->updateCustomer(['uniacid' => $this->_uniacid ,'pid' => $input['staff_id']] ,['pid' => $input['to_staff_id']]);


        //collection
        $need_del_collection_ids = [];
        $collection_model = new CollectionModel();
        $staff_collection_ids = [];
        //获取交接员工的客户信息
        $staff_collections = $collection_model->listCollection(['uniacid' => $this->_uniacid ,'to_uid' => $input['staff_id']]);
        foreach($staff_collections as $collection)
        {
            $old_collection_ids[$collection['uid']] =  $collection['id'];
        }
        //获取接受员工的客户信息
        $to_staff_collection_ids = [];
        $to_staff_collections = $collection_model->listCollection(['uniacid' => $this->_uniacid ,'to_uid' => $input['to_staff_id']]);
        foreach($to_staff_collections as $collection){
            if(isset($old_collection_ids[$collection['uid']])) $need_del_collection_ids[] = $old_collection_ids[$collection['uid']];
        }
        //删除已经存在的客户
        $collection_model->delCollection([['uniacid' ,'=' ,$this->_uniacid] ,['id' ,'in' ,$need_del_collection_ids]]);
        //更新客户信息
        $collection_model = new CollectionModel();
        $collection_model->updateCollection(['to_uid' => $input['staff_id']] ,['to_uid' => $input['to_staff_id'],'handover_name'=>$staff['name']]);
        //client_info
        $client_info_model = new ClientInfoModel();
        $client_info_model->updateClientInfo(['staff_id' => $input['staff_id']] ,['staff_id' => $input['to_staff_id']]);

        
        if(isset($input['is_dynamic']) && !empty($input['is_dynamic']))
        {
            $timeline_model = new CardTimeline();
            $timeline_model->updateTimeline(['uniacid' => $this->_uniacid ,'user_id' => $input['staff_id']] ,['user_id' => $input['to_staff_id']]);
        }
        //取消员工名片
        $user_model     = new UserModel();
        $result         = $user_model->updateUser(['id' => $input['staff_id'] ,'uniacid' => $this->_uniacid] ,['is_staff' => 0,'is_boss' => 0]);

        if($result)
        {
            longbingGetUser($input['staff_id'] ,$this->_uniacid ,true);
            $info_model = new UserInfoModel();
            $result = $info_model->updateUser(['fans_id' => $input['staff_id'] ,'uniacid' => $this->_uniacid] ,['is_staff' => 0]);
            if($result)
            {
//              $staff['is_staff'] = 0;
//              longbingSetUserInfo($input['staff_id'] ,$this->_uniacid ,$staff);
                longbingGetUserInfo($input['staff_id'] ,$this->_uniacid ,true);
            }
        }


        //更新雷达消息
        $RadarCount = new RadarCount();

        $RadarCount->where(['uniacid'=>$this->_uniacid,'to_uid'=>$input['staff_id']])->update(['to_uid'=>$input['to_staff_id']]);
        //添加日志
        $log_data = [
          'uniacid'     => $this->_uniacid,
          //交接员工
          'staff_id'    => $input['staff_id'],
          //被交接员工
          'to_staff_id' => $input['to_staff_id'],
          //是否交接动态
          'timeline'    => !empty($input['is_dynamic'])?1:0,
          //是否交接名片码
          'card_qr'     => !empty($input['card_qr'])?1:0,
          //类型
          'type'        => 1,
          //操作人员
          'action_user' => $this->getAdminInfo()
        ];
        //日志模型
        $StaffHand_model = new StaffHand();
        //添加日志
        $res = $StaffHand_model->addLog($log_data);
        //跟进记录
        $follow_model = new UserFollow();

        $follow_model->where(['staff_id'=>$input['staff_id']])->update(['staff_id'=>$input['to_staff_id']]);


        return  $this->success($result);
    }


    /**
     * @author chenniang
     * @DataTime: 2020-01-10 16:52
     * @功能说明:获取用户登陆名字
     */
     public function getAdminInfo(){
         if(!longbingIsWeiqin()){
             $name = $this->_user['account'];
         }else{
             global $_GPC, $_W;
             $name = !empty($_W['user']['username'])?$_W['user']['username']:'';
         }
        return $name;
     }


    //获取话术分类列表
    public function listReplyType()
    {
        //获取数据
        $param = $this->_param;
        //生成查询
        $filter = ['uniacid' => $this->_uniacid];
        if(isset($param['title'])) $filter['title'] = $param['title'];
        if(isset($param['status'])) $filter['status'] = $param['status'];
        //默认分页
        $page_config = array(
            'page' => 1,
            'page_count' => 20
        );
        
        //获取分页信息
        if(isset($param['page']) && $param['page'] > 0) $page_config['page'] = $param['page'];
        if(isset($param['page_count']) && $param['page_count'] > 0) $page_config['page_count'] = $param['page_count'];
        //生成分类模型
        $type_model = new ReplyTypeModel();
        $types      = $type_model->listType($filter ,$page_config);
        $page_config['total'] =  $type_model->getTypeCount($filter);  
        $page_config['total_page'] = (int)($page_config['total'] / $page_config['page_count']);
        if(($page_config['total'] % $page_config['page_count']) > 0) $page_config['total_page'] = $page_config['total_page'] + 1;
        //生成返回数据
        $result  = $page_config;
        $result['data'] = $types;
        return $this->success($result);
    }
    //添加话术分类
    public function addReplyType()
    {
        //获取数据
        $input = $this->_input;
        if(isset($input['data'])) $input = $input['data'];
        //判断数据是否存在
        if(!isset($input['title'])) return $this->error(lang('not repley type data'));
        $input['uniacid'] = $this->_uniacid;
        //生成模型
        $type_model = new ReplyTypeModel();
        $result     = $type_model->createType($input);
        return $this->success($result);
        
    }
    //修改话术分类
    public function updateReplyType()
    {

        //获取数据
        $input = $this->_input;
        if(isset($input['data'])) $input = $input['data'];
        if(empty($input['id'])) return $this->error(lang('not repley type data'));
        //判断数据是否存在
        $type_model = new ReplyTypeModel();
        $type_id    = $input['id'];unset($input['id']);
        $result     = $type_model->updateType(['uniacid' => $this->_uniacid ,'id' => $type_id] ,$input);
        return $this->success($result);
    }
    //删除话术分类
    public function delReplyType()
    {
        //获取数据
        $param = $this->_param;
        if(!isset($param['type_id'])) return $this->error(lang('not type id'));
        //生成模型
        $type_model = new ReplyTypeModel();
        //删除
        $result     = $type_model->delType(['id' => $param['type_id'] ,'uniacid' => $this->_uniacid]);
        if(!empty($result))
        {
            $reply_model = new ReplyModel();
            $reply_model->deleteReply(['type' => $param['type_id'] ,'uniacid' => $this->_uniacid]);
        }
        return $this->success($result);
    }
    //获取话术列表
    public function listReply()
    {
        //获取查询数据
        $param = $this->_param;
        $filter = [];
        if(isset($param['content'])) $filter['content'] = $param['content'];
        $filter['uniacid'] = $this->_uniacid;
        $filter['user_id'] = 0;
        //默认分页
        $page_config = array(
            'page' => 1,
            'page_count' => 20
        );
        
        //获取分页信息
        if(isset($param['page']) && $param['page'] > 0) $page_config['page'] = $param['page'];
        if(isset($param['page_count']) && $param['page_count'] > 0) $page_config['page_count'] = $param['page_count'];
        //生成话术模型
        $reply_model = new ReplyModel();
        $replys      = $reply_model->listReplys($filter ,$page_config);
        $page_config['total'] =  $reply_model->getReplyCount($filter);  
        $page_config['total_page'] = (int)($page_config['total'] / $page_config['page_count']);
        if(($page_config['total'] % $page_config['page_count']) > 0) $page_config['total_page'] = $page_config['total_page'] + 1;
        //生成返回数据
        $result  = $page_config;
        $result['data'] = $replys;
        return $this->success($result);
        
    }
    //添加话术
    public function addReply()
    {
        //获取数据
        $input = $this->_input;
        if(isset($input['data'])) $input = $input['data'];
        if(!isset($input['content'])) $this->error('not reply content');
        //判断type是否存在
        if(isset($input['type'])){
            $type_model = new ReplyTypeModel();
            $count      = $type_model->getTypeCount(['uniacid' => $this->_uniacid ,'id' => $input['type']]);
            if(empty($count)) return $this->error(lang('not repley type data'));
        }
        $input['uniacid'] = $this->_uniacid;
        $input['user_id'] = 0;
        //创建数据
        $reply_model = new ReplyModel();
        $result      = $reply_model->createReply($input);
        //返回数据
        return $this->success($result);
    }
    //修改话术
    public function updateReplys()
    {
        //获取数据
        $input = $this->_input;
        if(isset($input['data'])) $input = $input['data'];
        //检查数据是否存在
        if(!isset($input['id'])) $this->error(lang('not reply content'));

        //判断数据是否存在
        $id = $input['id'];
        unset($input['id']);
        $reply_model = new ReplyModel();
        $result      = $reply_model->updateReply(['id' => $id ,'uniacid' => $this->_uniacid] ,$input);
        return $this->success($result);
    }
    //删除话术
    public function delReply()
    {
        //获取数据
        $param = $this->_param;
        //判断id是否存在
        if(!isset($param['id'])) return $this->error(lang('not reply content'));
        //删除数据
        $reply_model = new ReplyModel();
        $result      = $reply_model->deleteReply(['id' => $param['id'] ,'uniacid' => $this->_uniacid]);
        return $this->success($result);
    }
    //获取问卷列表
    public function listQuestionnair()
    {
        //获取参数
        $param = $this->_param;
        //默认分页
        $page_config = array(
            'page' => 1,
            'page_count' => 20
        );
        
        //获取分页信息
        if(isset($param['page']) && $param['page'] > 0) $page_config['page'] = $param['page'];
        if(isset($param['page_count']) && $param['page_count'] > 0) $page_config['page_count'] = $param['page_count'];
        //获取数据
        $questionnaire_model = new QuestionnaireModel();
                                                   
        $data               = $questionnaire_model->listQuestionnaire(['uniacid' => $this->_uniacid] ,$page_config);
        
        $page_config['total'] =  $questionnaire_model->getQuestionnaireCount(['uniacid' => $this->_uniacid]);  
        $page_config['total_page'] = (int)($page_config['total'] / $page_config['page_count']);
        if(($page_config['total'] % $page_config['page_count']) > 0) $page_config['total_page'] = $page_config['total_page'] + 1;
        //生成返回数据
        $result  = $page_config;
        $result['data'] = $data;
        return $this->success($result);
    }
    
    //获取调查问卷详情
    public function getQuestionnair()
    {
        //获取参数
        $param = $this->_param;
        if(!isset($param['id'])) return $this->error(lang('not questionnair id'));
        //获取数据
        $questionnaire_model = new QuestionnaireModel();
        $data = $questionnaire_model->getQuestionnaire(['id' => $param['id'] ,'uniacid' => $this->_uniacid]);
        return $this->success($data);
    }
    
    //添加问卷列表
    public function addQuestionnair()
    {
        //获取数据
        $input = $this->_input;
        //获取数据
        if(isset($input['data'])) $input = $input['data'];
        if(!isset($input['title']) || empty($input['title'])) $this->error(lang('not questionnair'));
        //创建问卷
        $questionnaire_data  = ['title' => $input['title'] ,'uniacid' => $this->_uniacid];
        longbingCardsetAllQuestionnaire(['uniacid' => $this->_uniacid] ,['status' => 0]);
        $questionnaire_model = new QuestionnaireModel();
        $questionnaire_id = $questionnaire_model->createQuestionnaire($questionnaire_data);
        //创建问卷问题
        if(!empty($questionnaire_id) && isset($input['question']))
        {
            foreach($input['question'] as $val)
            {
                if(isset($val['title']) && !empty($val['title']))
                {
                    $data = ['title' => $val['title'] ,'uniacid' => $this->_uniacid ,'naire_id' => $questionnaire_id];
                    $question_model = new QuestionModel();
                    $question_model->createQuestion($data);
                }
            }
        } 
        //返回数据
        return $this->success(!empty($questionnaire_id));
    } 
    //修改问卷列表
    public function updateQuestionnairs()
    {
        //获取数据
        $input = $this->_input;
        if(isset($input['data'])) $input = $input['data'];
        if(!isset($input['id']) || empty($input['id'])) return $this->error(lang('not questionnair id'));
        //数据处理
        $id = $input['id'];
        //获取问卷详情
        $questionnaire_model = new QuestionnaireModel();
        $questionnaire = $questionnaire_model->getQuestionnaire(['id' => $id ,'uniacid' => $this->_uniacid]);
//        var_dump($questionnaire);die;
        //判断数据是否存在
        if(empty($questionnaire)) return $this->success(false);
        if(isset($input['status']))
        {
            //如果开启问卷，关闭其他问卷
            if(isset($input['status']) && !empty($input['status'])) longbingCardsetAllQuestionnaire($this->_uniacid,['status' => 0]);
            $qn_model = new QuestionnaireModel();
            $result = $qn_model->updateQuestionnaire(['id' => $id] ,$input);
        }else{
            //获取存在的问题ids
            $question_ids = [];
            if(isset($questionnaire['question']))
            {
                foreach($questionnaire['question'] as $val)
                {
                    if(isset($val['id'])) $question_ids[] = $val['id'];
                }
            }
            //数据处理
            unset($input['id']);
            $question = []; 
            if(isset($input['question'])) $question = $input['question'];
            unset($input['question']);
            $result = true;
            //修改问卷状态和标题
            if(!empty($input)) {
                //如果开启问卷，关闭其他问卷
                if(isset($input['status']) && !empty($input['status'])) longbingCardsetAllQuestionnaire($this->_uniacid,['status' => 0]);
                $qn_model = new QuestionnaireModel();
                $result = $qn_model->updateQuestionnaire(['id' => $id] ,$input);        
            }
            //修改问题
            foreach($question as $key => $val)
            {
                $question_model = new QuestionModel();
                if(isset($val['id']) && !empty($val['id']) && in_array($val['id'], $question_ids))
                {
                    //从$question_ids删除id
                    $q_id = $val['id']; unset($val['id']);
                    $question_ids = array_diff($question_ids ,[$q_id]);
                    $question_model->updateQuestion(['id' => $q_id] ,$val);
                }else{
                    if(isset($val['id'])) unset($val['id']);
                    $val['uniacid'] = $this->_uniacid;
                    $val['naire_id'] = $id;
                    $question_model->createQuestion($val);
                }
            }
            //删除不需要的问题
            if(!empty($question_ids)){
                $question_model = new QuestionModel();
                $question_model->delQuestionById($question_ids);
            }
        }
        return $this->success($result);
    }
    //删除问卷列表
    public function delQuestionnair()
    {
        //获取参数
        $param = $this->_param;
        if(!isset($param['id'])) return $this->error(lang('not questionnair id'));
        //删除
        $questionnaire_model = new QuestionnaireModel();
        $result = $questionnaire_model->delQuestionnaire(['id' => $param['id'] ,'uniacid' => $this->_uniacid]);
        if(!empty($result))
        {
            $question_model = new QuestionModel();
            $question_model->delQuestion(['naire_id' => $param['id'] ,'uniacid' => $this->_uniacid]);
        }
        return $this->success($result);
    } 
    //设置问卷信息
    public function setQuestionnairConfig()
    {
        //获取数据
        $input = $this->_input;
        if(isset($input['data'])) $input = $input['data'];
        if(empty($input)) return $this->error(lang('not questionnair Config data'));
        $config = longbingGetAppConfig($this->_uniacid);
        if(empty($config)) return $this->error(lang('not questionnair Config data'));
        //修改设置
        $config_model = new QuestionnairConfig();
        $result       = $config_model->updateConfig(['uniacid' => $this->_uniacid] ,$input);
        //修正缓存
        longbingGetAppConfig($this->_uniacid ,true);
        //返回数据
        return $this->success($result);
    }
    //获取问卷设置
    public function getQuestionnairConfig()
    {
        $result = [];
        $config = longbingGetAppConfig($this->_uniacid);
        if(isset($config['question_switch'])) $result['question_switch'] = $config['question_switch'];
        if(isset($config['question_text'])) $result['question_text'] = $config['question_text'];
        return $this->success($result);
    }


    /**
     * @author chenniang
     * @DataTime: 2020-02-14 15:27
     * @功能说明:导入excel的客户（暂时不需要）
     */
    public function importExcelCustomer(){
        $input = $this->_input;
        //excel 类
        $excel = new Excel();
        //读取excel的数据
        $data = $excel->readExcel($input['filename']);
        //判断返回类型
        if(empty($data)||!is_array($data)){
            return $this->error('文件类型错误');
        }

        //导入
        $res = $this->importExcelAction($data);

        return $this->success($res);

    }

    /**
     * @author chenniang
     * @DataTime: 2020-02-14 15:27
     * @功能说明:导入客户
     */
    public function importCustomer(){
        $data = $this->_input['data'];

        //导入
        $res = $this->importExcelAction($data);

        return $this->success($res);

    }
    /**
     * @author chenniang
     * @DataTime: 2020-02-14 15:27
     * @功能说明:导入excel的客户
     */
    public function importExcelAction($data){

        $customer_model = new UserModel();

        foreach ($data as $k=>$v){
//            //如果为空直接跳过
//            if (!$v[0]) {
//                continue;
//            }
            $list = [
                //openid
                'openid'    => 'import-' . uniqid() . rand(10000, 99999) . $k,
                //昵称
                'nickName'  => $v['nickName'],
                //头像
                'avatarUrl' => $v['avatarUrl'] ? $v['avatarUrl'] : '',
                //uniacid
                'uniacid'   => $this->_uniacid,
                //导入标示
                'import'    => 1,
                //创建时间
                'create_time' => time(),
                //更新时间
                'update_time' => time()
            ];
            //插入
            $customer_model->insert($list);
            //uid
            $uid = $customer_model->getLastInsID();

            //电话插入类容
            $phone = [
                //用户id
                'user_id' => $uid,
                //uniacid
                'uniacid' => $this->_uniacid,
                //电话
                'phone'   => $v['phone'],
                //
                'to_uid'  => 0,
            ];

            Db::name('longbing_card_user_phone')->insert($phone);

        }
        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-02-17 16:08
     * @功能说明:获取下载地址
     */
    public function getExcelPath(){
        //实例化excel的类
        $excel = new Excel();
        //名字
        $name  ='导入客户';
        //标题
        $header=[
            '昵称',
            '电话',
            '头像链接',
        ];
        //导出
        $fileName=$excel->excelExport($name,$header,[]);

        return $this->success($fileName);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-16 11:42
     * @功能说明:
     */
    public function updateUserInfo(){

        $input = $this->_input;

        $user_model = new IndexUser();

        $phone_model= new UserPhone();

        $user_update = [

            'nickName' => $input['nickName'],

            'gender'   => $input['gender'],

            'birthday' => $input['birthday'],

        ];
        //修改用户信息
        $user_model->where(['id'=>$input['id']])->update($user_update);
        //查询电话信息
        $phone_info = $phone_model->where(['user_id'=>$input['id']])->find();

        $last_staff_id = $user_model->where(['id'=>$input['id']])->value('last_staff_id');
        //编辑电话信息
        if(empty($phone_info)){

            $insert  = [

                'uniacid' => $this->_uniacid,

                'user_id' => $input['id'],

                'to_uid'  => $last_staff_id,

                'phone'   => $input['phone'],

                'status'  => 1,

                'create_time' => time(),

                'update_time' => time(),
            ];

            $phone_model->insert($insert);

        }else{

            $phone_model->where(['id'=>$phone_info->id])->update(['phone'=>$input['phone']]);

        }

        $key = 'longbing_card_user_' . $input['id'];

        if(hasCache($key,$this->_uniacid)){

            delCache($key,$this->_uniacid);
        }

        return $this->success(true);

    }
}
 